<template>
  <!-- 外呼任务 -->
  <div v-loading="pageLoading" class="ceateEditor">
    <div class="ceateEditorHeight" style="display: flex">
      <div class="text">{{ $route.query.editFlag == '3' ? '任务详情' : $route.query.editFlag == '2' ? '编辑外呼任务' : '创建外呼任务' }}</div>
      <div class="button">
        <el-button :loading="loading" type="primary" @click="submitButton('form')" v-if="['1','2'].indexOf($route.query.editFlag) !== -1">确定</el-button>
        <el-button @click="$router.go(-1)">返回</el-button>
      </div>
    </div>

    <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="$route.query.editFlag == '3'">
      <el-card>
        <div slot="header">
          <div class="titleboxstyle"></div>
          <span style="font-weight: 500;">基础设置</span>
        </div>

        <el-form-item label="外呼任务" prop="taskName">
          <el-input v-model.trim="form.taskName" clearable placeholder="请输入外呼名称" style="width: 240px"/>
        </el-form-item>

        <el-form-item prop="ocLeadNo">
          <template slot="label">
            <span class="before-hasValue">拓客线索</span>
          </template>
          <check-number-base ref="checkNumberBase" v-model="form.ocLeadNo" :disabled="$route.query.editFlag == '3'"></check-number-base>
        </el-form-item>

        <el-form-item label="BOT" prop="dialogFlowId">
          <el-select v-model="form.dialogFlowId" clearable placeholder="请选择" style="width: 240px;" @change="changeBot">
            <el-option v-for="item in botList" :key="item.dialogFlowId" :label="item.name" :value="item.dialogFlowId"/>
          </el-select>
        </el-form-item>

        <el-form-item label="呼叫线路" prop="callLinkId">
          <el-select v-model="form.callLinkId" clearable multiple placeholder="请选择" style="width: 240px;">
            <el-option v-for="item in callLinkList" :key="item.tenantPhoneNumberId" :label="item.phoneNumber"
                       :value="item.tenantPhoneNumberId"/>
          </el-select>
        </el-form-item>

        <el-form-item label="任务执行时间" prop="startTime">
          <el-date-picker v-model="form.startTime" :picker-options="pickerOptions" format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择日期"
                          style="width: 240px;" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item>

        <el-form-item label="并发数量" prop="robotCount">
          <el-input-number v-model="form.robotCount" :min="1" :precision="0" :step="1" label="描述文字" :max="reRobotCount"/>
          <span style="font-size: 12px;">人</span>
        </el-form-item>
      </el-card>

      <el-card style="margin-top: 20px;">
        <div slot="header">
          <div class="titleboxstyle"></div>
          <span style="font-weight: 500;">自动执行添加设置</span>
          <span class="gray-text">
            <i class="el-icon-warning" style=";margin-right: 10px;"></i>
            <span>外呼任务完成后将自动执行申请添加A类意向客户为好友，请保持超级企微在线</span>
          </span>
        </div>

        <el-form-item label="加好友">
          <el-switch v-model="form.addFriendFlag" active-color="#082aff" inactive-color="#DCDFE6"/>
        </el-form-item>

        <el-form-item prop="digitalEmployeesId" v-if="form.addFriendFlag">
          <template slot="label">
            <span class="before-hasValue">超级企微</span>
          </template>
<!--          <check-digital-employee ref="checkDigitalEmployee" v-model="form.digitalEmployeesId" :is-single-option="isSingleOption" :disabled="$route.query.editFlag == '3'"></check-digital-employee>-->
          <select-supermicro ref="checkDigitalEmployee" v-model="form.digitalEmployeesId" :is-single-option="isSingleOption" :disabled="$route.query.editFlag == '3'"></select-supermicro>
        </el-form-item>

        <el-form-item label="验证语">
          <el-switch v-model="form.vlFlag" active-color="#082aff" inactive-color="#DCDFE6"/>
        </el-form-item>

        <div v-if="form.vlFlag">
          <el-form-item label="">
            <el-input v-model="form.vlMsg" :rows="4" maxlength="50"
                      placeholder="验证语最大长度为50个汉字，用作请求添加好友的话术，支持文字、数字、特殊字符等"
                      show-word-limit
                      style="width: 500px;"
                      type="textarea">
            </el-input>
          </el-form-item>

          <!-- <el-form-item label="欢迎语">
            <NormalSelectMaterial :selectedList="form.welcomeMsg" @confirmSelect="confirmSelectFn"/>
          </el-form-item> -->
          <el-form-item label="打标签">
            <tag-group v-model="form.label" :disabled="$route.query.editFlag == '3'"/>
          </el-form-item>
          <el-form-item v-if="customerLabelList.length == 2" label="是否客户" label-width="70px"
                        prop="customerLabel" style="margin-left: 120px!important">
            <el-radio-group v-model="form.customerLabel">
              <el-radio-button :label="customerLabelList[0].tagId" class="radio-btn" style="margin-right: 20px;">
                {{ customerLabelList[0].name }}
              </el-radio-button>
              <el-radio-button :label="customerLabelList[1].tagId" class="radio-btn">{{
                  customerLabelList[1].name
                }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="打备注">
            <el-switch v-model="form.noteFlag" active-color="#082aff" inactive-color="#DCDFE6"/>
          </el-form-item>

          <el-form-item v-if="form.noteFlag" label="">
            <el-input v-model="form.note" :rows="4" maxlength="100" placeholder="请输入备注内容" show-word-limit
                      style="width: 500px;"
                      type="textarea">
            </el-input>
          </el-form-item>
        </div>

        <el-form-item label="发送短信方式">
          <el-radio-group v-model="form.sendMsgType" style="margin-top: 10px;">
            <el-radio label="2">手动发送引流链接 <span
              class="gray-text">选择后需在任务明细中手动触发发送引流链接短信</span></el-radio>
            <br>
            <el-radio label="1" style="margin-top: 10px;">自动发送引流链接 <span
              class="gray-text">选择后将自动执行发送引流链接短信</span></el-radio>
          </el-radio-group>
        </el-form-item>

        <div><span
          style="display: inline-block;width: 120px;text-align: right;margin: 10px 0 5px;">引流链接设置</span><span
          class="gray-text">执行添加企微任务完成后需手动在后台点击发送引流链接至客户短信</span></div>
        <el-form-item prop="hkLink">
          <template slot="label">
            <span class="before-hasValue">引流链接</span>
          </template>
          <check-drainage-link ref="checkDrainageLink" v-model="form.hkLink" :disabled="$route.query.editFlag == '3'"/>
        </el-form-item>

      </el-card>

      <el-card style="margin-top: 20px;">
        <div slot="header">
          <div class="titleboxstyle"></div>
          <span style="font-weight: 500;">二次外呼任务设置</span>
        </div>

        <el-form-item label="是否开启">
          <el-switch v-model="form.repeatedlyFlag" active-color="#082aff" inactive-color="#DCDFE6"/>
          <span class="gray-text">开启二次外呼任务后，将向还未添加员工的A类B类客户执行二次外呼任务</span>
        </el-form-item>
        <div v-if="form.repeatedlyFlag">
          <el-form-item label="BOT" prop="dialogFlowId2">
            <el-select v-model="form.dialogFlowId2" clearable placeholder="请选择" style="width: 240px;">
              <el-option v-for="item in botList" :key="item.dialogFlowId" :label="item.name"
                         :value="item.dialogFlowId"/>
            </el-select>
          </el-form-item>

          <el-form-item label="呼叫线路" prop="reCallLink">
            <el-select v-model="form.reCallLink" clearable multiple placeholder="请选择" style="width: 240px;">
              <el-option v-for="item in callLinkList" :key="item.tenantPhoneNumberId" :label="item.phoneNumber"
                         :value="item.tenantPhoneNumberId"/>
            </el-select>
          </el-form-item>

          <el-form-item label="任务执行时间" prop="reCallTime">
            <el-input-number v-model="form.reCallTime" :min="1"  :precision="0"  :step="1" label="描述文字"/>
            <span
              style="font-size: 12px;">小时后未添加员工开始执行二次外呼任务</span>
          </el-form-item>
          <el-form-item label="并发数量" prop="reRobotCount">
            <el-input-number v-model="form.reRobotCount" :min="1" :step="1" :precision="0" label="描述文字" :max="reRobotCount"/>
            <span
              style="font-size: 12px;">人</span>
          </el-form-item>

          <div><span
            style="display: inline-block;width: 120px;text-align: right;margin: 10px 0 5px;">引流链接设置</span><span
            class="gray-text">执行添加企微任务完成后需手动在后台点击发送引流链接至客户短信</span></div>
          <el-form-item prop="reHkLink">
            <template slot="label">
              <span class="before-hasValue">引流链接</span>
            </template>
            <check-drainage-link ref="checkDrainageLink" v-model="form.reHkLink" :disabled="$route.query.editFlag == '3'"/>
          </el-form-item>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<script>
import checkDrainageLink from '@/components/checkDrainageLink.vue';
import checkNumberBase from "@/components/checkNumberBase.vue";
import checkDigitalEmployee from "@/components/checkDigitalEmployee.vue";
import selectSupermicro from "@/components/selectSupermicro.vue";
import {
  createIocTask,
  editIocTask,
  queryBotList,
  queryCallLinkList,
  queryCustomerLabelList,
  queryIocTaskInfo
} from '@/api/intelligentOutCall/index'
import moment from "moment";

export default {
  components: {checkDrainageLink, checkNumberBase, checkDigitalEmployee, selectSupermicro },
  neme: 'IntelligentOutCallDetail',
  data() {
    const checkdialogFlowId = (rule, value, callback) => {
      console.log('触发校验')
      if (this.form.repeatedlyFlag && value == this.form.dialogFlowId) {
        callback(new Error('二次外呼任务与第一次任务BOT不能相同'));
      } else {
        callback();
      }
    }
    const reRobotCount = +window.globalConfig.MAX_ROBOTCOUNT || 100
    return {
      pageTitle: '创建外呼任务',
      loading: false,
      form: {
        taskName: '',
        ocLeadNo: [],
        dialogFlowId: null,
        callLinkId: [],
        startTime: null,
        robotCount: null,
        digitalEmployeesId: [],
        addFriendFlag: true,
        vlFlag: false,
        vlMsg: '',
        welcomeMsg: [],
        label: null,
        customerLabel: null,
        noteFlag: false,
        note: null,
        sendMsgType: '2',
        hkLink: [],
        repeatedlyFlag: false,
        dialogFlowId2: null,
        reCallLink: [],
        reCallTime: null,
        reRobotCount: null,
        reHkLink: [],
      },
      botList: [],
      callLinkList: [],
      rules: {
        taskName: [{required: true, trigger: 'blur', message: '请输入外呼名称'},
          {max: 20, message: '名称输入有误，请重新输入', trigger: 'blur'}],
        dialogFlowId: [{required: true, trigger: 'change', message: '请选择BOT'}],
        callLinkId: [{required: true, trigger: 'change', message: '请选择呼叫线路'}],
        startTime: [{required: true, trigger: 'change', message: '请选择任务执行时间'}],
        robotCount: [{required: true, trigger: 'change', message: '请输入并发数量'}],
        sendMsgType: [{required: true, trigger: 'change', message: '请选择发送短信方式'}],
        dialogFlowId2: [
          {required: true, trigger: 'change', message: '请选择BOT'},
          // { validator: checkdialogFlowId, trigger: ['change','blur'] }
        ],
        reCallLink: [{required: true, trigger: 'change', message: '请选择呼叫线路'}],
        reCallTime: [{required: true, trigger: 'change', message: '请输入任务执行超时时间'}],
        reRobotCount: [{required: true, trigger: 'change', message: '请输入并发数量'}],
      },
      customerLabelList: [], //是否客户标签组
      pageLoading: false,
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() <=
            (new Date().getTime() - 24 * 60 * 60 * 1000)
          );
        },
      },

      isSingleOption: false,
      reRobotCount: reRobotCount
    }
  },
  methods: {
    changeBot(){
      if(this.form.repeatedlyFlag && this.form.dialogFlowId2) {
         this.$nextTick(() => {
           this.$refs['form'].validateField('dialogFlowId2')
         })
      }
    },
    submitButton() {
      if (!this.form.ocLeadNo || this.form.ocLeadNo.length == 0) {
        return this.$message.error('请选择拓客线索')
      }
      if ((!this.form.digitalEmployeesId || this.form.digitalEmployeesId.length == 0) && this.form.addFriendFlag) {
        return this.$message.error('请选择超级企微')
      }
      if (!this.form.hkLink || this.form.hkLink.length == 0) {
        return this.$message.error('请选择引流链接')
      }
      if ((!this.form.reHkLink || this.form.reHkLink.length == 0) && this.form.repeatedlyFlag) {
        return this.$message.error('请选择二次外呼引流链接')
      }
      this.$refs['form'].validate((valid) => {
        console.log('valid', valid);
        if (valid) {
          let obj = {
            ...this.form,
            repeatedlyFlag: this.form.repeatedlyFlag ? '1' : '0',
            noteFlag: this.form.noteFlag ? '1' : '0',
            vlFlag: this.form.vlFlag ? '1' : '0',
            addFriendFlag: this.form.addFriendFlag ? '1' : '0',
            ocLeadNo: this.form.ocLeadNo[0]?.ocLeadNo,
            ocLeadName: this.form.ocLeadNo[0]?.ocLeadName,
            hkLink: this.form.hkLink,
            reHkLink: this.form.reHkLink,
            digitalEmployeesId: this.form.addFriendFlag ? this.form.digitalEmployeesId : [],
            botName: this.botList.some(item => item.dialogFlowId == this.form.dialogFlowId) ? this.botList.filter(item => item.dialogFlowId == this.form.dialogFlowId)[0].name : '',
            reBotName:this.botList.some(item => item.dialogFlowId == this.form.dialogFlowId2) && this.form.dialogFlowId2 ? this.botList.filter(item => item.dialogFlowId == this.form.dialogFlowId2)[0].name : ''
          }
          console.log(obj, 'form+obj')
          this.pageLoading = true
          if(this.$route.query.id){
            obj.taskNo = this.$route.query.id
            editIocTask(obj).then(res => {
              if (res.code == 200) {
                this.$message.success('编辑成功')
                this.pageLoading = false
                this.$router.go(-1)
              }
            }).catch(() => { this.pageLoading = false })
          }else{
            createIocTask(obj).then(res => {
              if (res.code == 200) {
                this.$message.success('新增成功')
                this.pageLoading = false
                this.$router.go(-1)
              }
            }).catch(() => { this.pageLoading = false })
          }
        }
      })
    },
    // 确定选择的素材
    confirmSelectFn(val) {
      this.form.welcomeMsg = val;
    },
    // 获取详情
    getDetail(){
      queryIocTaskInfo({taskNo: this.$route.query.id}).then(res => {
        if(res.code == 200){
          let obj = {
            ...res.data,
            repeatedlyFlag: res.data.repeatedlyFlag == '1' ? true : false,
            noteFlag: res.data.noteFlag == '1' ? true : false,
            vlFlag: res.data.vlFlag == '1' ? true : false,
            addFriendFlag: res.data.addFriendFlag == '1' ? true : false,
            ocLeadNo: res.data.ocLeadNo?  [{ocLeadNo: res.data.ocLeadNo, ocLeadName: res.data.ocLeadName}]: [] ,
            hkLink: res.data.hkLink || [],
            reHkLink: res.data.reHkLink || [],
            digitalEmployeesId: res.data.digitalEmployeesId || [],
            welcomeMsg: res.data.welcomeMsg || [],
            label: res.data.label || []
          }
          console.log(obj.ocLeadNo, 'leadNo')
          this.$set(this, 'form', obj)
        }
      })
    },
  },
  mounted() {
    queryBotList().then(res => {
      this.botList = res.code == 200 ? res.data : []
    }).catch(() => {
      this.botList = []
    })
    queryCallLinkList().then(res => {
      this.callLinkList = res.code == 200 ? res.data : []
    }).catch(() => {
      this.callLinkList = []
    })
    queryCustomerLabelList().then(res => {
      if(res.code == 200){
        this.customerLabelList =  res.data || []
        this.form.customerLabel = this.customerLabelList?.[0].tagId
      }
    }).catch(() => {
      this.customerLabelList = []
    })
    this.$set(this.form, 'sendMsgType', '1')
    if(this.$route.query.id && (this.$route.query.editFlag == '2' || this.$route.query.editFlag == '3')) this.getDetail()
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.ceateEditor {
  .ceateEditorHeight {
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    background-color: white;
    height: 70px;
    padding-left: 20px;
    padding-right: 20px;
    border-radius: 6px;

    .text {
      font-size: 20px;
    }
  }
}

.titleboxstyle {
  position: absolute;
  display: inline-block;
  width: 3px;
  height: 14px;
  background-color: #082aff;
  left: 0px;
  // margin-left: -20px;
}

.radio-btn {
  :last-child {
    border-left: 1px solid #DCDFE6;
    border-radius: 4px;
    box-shadow: none !important;
  }

}

.gray-text {
  color: #CCC;
  margin-left: 20px;
  font-size: 12px;
}

.before-hasValue::before {
  content: "*";
  color: #e74e59;
  margin-right: 4px;
}
</style>
